package com.lyeducation.controllers.system;

import com.lyeducation.controllers.base.BaseController;
import com.lyeducation.controllers.dto.RequestDto;
import com.lyeducation.controllers.dto.UserDto;
import com.lyeducation.controllers.dto.system.InsertUpdSysMenuDto;
import com.lyeducation.controllers.dto.system.ShowInsertUpdateSysMenuDto;
import com.lyeducation.core.base.SysConstants;
import com.lyeducation.core.system.SysMenuService;
import com.lyeducation.entities.system.SysMenuEntity;
import com.lyeducation.security.config.SecurityPrincipalContext;
import com.lyeducation.util.controllerUtil.JsonConstans;
import com.lyeducation.util.controllerUtil.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.TreeSet;

@Api(
  value = "菜单",
  tags = {"用户操作菜单接口,{mId}菜单id"},
  description = "菜单相关操作接口"
)
@RestController
@RequestMapping("sysMenu/{mId}")
public class SysMenuController extends BaseController<SysMenuEntity>
//    implements CrudService<HashMap<String, Object>, String>
{
  @Autowired private SysMenuService sysMenuService;

  // 登陆者的权限菜单信息
  @Override
  public JsonResult onLoad() {
    //    return JsonResult.putSuccess(SysUserUtils.getCurrentSysUser().getMenus());
    TreeSet<ShowInsertUpdateSysMenuDto> sysMenuDtos =
        ShowInsertUpdateSysMenuDto.createShowInsertUpdateSysMenuDtoSet(
            (TreeSet<SysMenuEntity>) sysMenuService.findData());
    return JsonResult.putSuccess(sysMenuDtos);
  }

  @GetMapping("dtoFxTest")
  public JsonResult dtoFxTest(@RequestBody RequestDto<UserDto> requestDto) {
    return JsonResult.putSuccess(requestDto);
  }

  @ApiOperation(
          value = "添加/更新菜单，json参数加id为更新",
          notes =
                  "{\"roleIdList\":[1],\"url\":\"course/delUserCourseScore\",\"name\":\"用户删除课程评分\",\"parentId\":\"1\",\"isNeedChildMenuRole\":true}"
  )
  @PostMapping("addSysMenu")
  public JsonResult addSysMenu(
      @ApiParam(name = "菜单item", value = "json", required = true) @RequestBody
          InsertUpdSysMenuDto sysMenuDto) {
    JsonResult jsonResult = checkParam(sysMenuDto);
    if (jsonResult != null) {
      return jsonResult;
    }
    return sysMenuService.insertUpdMenu(sysMenuDto);
  }

  @ApiOperation(value = "更新菜单", notes = "更新菜单，菜单权限")
  @ApiImplicitParam(
    name = "sysMenuDto",
    value = "菜单item",
    required = true,
    dataType = "SysMenuDto",
    paramType = "body"
  )
  @PostMapping("updSysMenu")
  public JsonResult updSysMenu(
      @RequestBody @Valid InsertUpdSysMenuDto sysMenuDto, BindingResult result) {
    JsonResult jsonResult = validation(result);
    if (jsonResult != null) {
      return jsonResult;
    }
    jsonResult = sysMenuDto.checkNumber("菜单id", sysMenuDto.getId());
    if (jsonResult != null) {
      return jsonResult;
    }
    jsonResult = checkParam(sysMenuDto);
    if (jsonResult != null) {
      return jsonResult;
    }
    sysMenuDto.setName(sysMenuDto.getName().trim());

    return sysMenuService.insertUpdMenu(sysMenuDto);
  }

  private JsonResult checkParam(InsertUpdSysMenuDto sysMenuDto) {
    JsonResult jsonResult = sysMenuDto.checkName("菜单名");
    if (jsonResult != null) {
      return jsonResult;
    }

    jsonResult = sysMenuDto.checkUrl();
    if (jsonResult != null) {
      return jsonResult;
    }
    if (sysMenuDto.getSort() > 0) {
      return JsonResult.putFail("排序无法小于0");
    }
    sysMenuDto.setUrl(sysMenuDto.getUrl().trim());
    sysMenuDto.setName(sysMenuDto.getName().trim());
    return null;
  }

  @ApiOperation(
          value = "根据id删除菜单")
  @GetMapping("delSysMenuById")
  public JsonResult delSysMenuById(String s) {
    if (SecurityPrincipalContext.getUserDetails().getAuthorities().size() == 1
            && SecurityPrincipalContext.getUserDetails()
            .getAuthorities()
            .iterator()
            .next()
            .getAuthority()
            .equals(SysConstants.PROJECT_ROLE_ADMIN.getValue())) {
      try {
        sysMenuService.delete(s, new HashMap<String, Object>());
      } catch (Exception e) {
        JsonResult.putFail(e.toString());
      }
      return JsonResult.putSuccess();
    }
    return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
  }

  @ApiOperation(
          value = "模糊查询菜单访问地址,需要管理员权限",
          notes =
                  "192.168.0.111:80/sysMenu/155823496235460664/findSysMenuByUrlLike?urlLike=video"
  )
  @GetMapping("findSysMenuByUrlLike")
  public JsonResult findSysMenuByUrl(String urlLike) {
    return JsonResult.putSuccess(sysMenuService.findSysMenuByUrlLike(urlLike));
  }

}
